#! /bin/bash
##### This is my (demuredemeanor) toggler script
# Source Code:  https://notabug.org/demure/scripts/src/master/toggler.sh
#
# This script is intended to be a scaleable invoker of various quick toggles I code.
# The inspiration was an AWK 'oneliner' that wasn't playing well with i3wm's bindsym+exec due to quotes/pipe.

NAME=$(basename "$0")

## Try to keep these strings up to date with the cases below
TOG_LIST="powersave, xss-lock, redshift"
BAR_LIST="polybar, utc, ip"

HELP="${NAME}: usage: [TOGGLE_NAME]\n\toptions: ${TOG_LIST}\n\tdemure's bar: ${BAR_LIST}"

if [[ $# -eq 1 ]]; then
    AUG="$1"

    case $AUG in
        ps|powersave)
            ## This is a little awk to toggle between having the screen power saving on/off. Helps keep music going through my external speakers when docked.¬ 
            xset q | awk 'BEGIN {C="xset -display :0.0"} /DPMS is/ {match($0,/DPMS is (.*)/,m)} END {if(m[1]=="Enabled"){D="-dpms";S="off";B="noblank"} else {D="dpms";S="on";B="blank"}} END {system(C" "D);system(C" s "S);system(C" s "B)}'
            ;;
        xl|xss-lock)
            ## kills xss-lock, or starts it
            pkill xss-lock || xss-lock -- i3block -e -c 2E3436 &
            ;;
        rs|redshift)
            ## Toggles redshift red mode
            pkill -USR1 redshift
            ;;


        ## polybar related section
        pb|polybar)
            ## Kill and restart polybar.
            $HOME/.config/polybar/scripts/start_polybar.sh
            ;;
        utc|UTC)
            ## A little toggle to go between local TZ and UTC in my fancy polybar
            awk -v TEMP=/tmp/i3_polybar_utc_${USER} 'BEGIN {{FILE=getline < TEMP < 0 ? "0" : "1"} {if($0==1){STATE=1} else {STATE=0}} {if(STATE==0){system("echo 1 > "TEMP)} else {system("echo 0 > "TEMP)}} }'
            ;;
        ip)
            ## A little trinary switch for toggling between showing/hiding the ip in my polybar
            awk -v TEMP=/tmp/i3_polybar_ip_toggle_${USER} 'BEGIN {{FILE=getline < TEMP < 0 ? "0" : "1"} {if($0==1){STATE=1} else {STATE=0}} {if(STATE==0){system("echo 1 > "TEMP)} else {system("echo 0 > "TEMP)}} }' 
            ;;
        *)
            echo "Bad augment."
            echo -e "${HELP}"
            ;;
    esac
elif [[ $# -gt 1 ]]; then
    echo "Too many augments!"
    echo -e "${HELP}"
else
    echo -e "${HELP}"
fi
